package com.yidushishizijie;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/*
* 抢车位：6辆车，3个车位，每辆车停3秒
* */

public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);//模拟资源类，有三个空车位
        for (int i = 1; i <=7 ; i++) {
            new Thread(() ->{
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"抢到了车位");
                    TimeUnit.SECONDS.sleep(3);//暂停一会儿线程，模拟停车时间
                    System.out.println(Thread.currentThread().getName()+"离开了车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }
    }
}
